package com.xuan.webfinally.controller;


import com.xuan.webfinally.entity.ApiData;
import com.xuan.webfinally.entity.clickWindow;
import com.xuan.webfinally.entity.environment;
import com.xuan.webfinally.entity.gaojingtanchuang;
import com.xuan.webfinally.entity.lxshuju;
import com.xuan.webfinally.entity.sbtongji;
import com.xuan.webfinally.entity.vediosAlls;
import com.xuan.webfinally.entity.wurenji;
import com.xuan.webfinally.service.IHomePageService;
import com.xuan.webfinally.service.ISlopeInfoService;
import com.xuan.webfinally.service.ISlopeWarningInfoService;
import com.xuan.webfinally.utils.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.*;


@RequiredArgsConstructor
@CrossOrigin(origins = "http://localhost:10002", maxAge = 3600)
@RestController
@RequestMapping("/home")
public class HomePageController {
    private final IHomePageService homePageService;
    private int valueofjcxm;
    private int valueofjcdays;



    @Autowired
    private ISlopeInfoService slopeInfoService;

    @Autowired
    private ISlopeWarningInfoService  slopeWarningInfoService;

    @GetMapping("/stats/monitor")
    public Result<List<Map<String, Object>>> getMonitorStats() {
        valueofjcxm = homePageService.getvalueofjcxm();
        // 起始日期：2025年5月1日
        LocalDate startDate = LocalDate.of(2025, 5, 1);

        // 当前日期：今天
        LocalDate today = LocalDate.now();

        // 计算天数差
        long daysBetween = ChronoUnit.DAYS.between(startDate, today);
        valueofjcdays = (int) daysBetween;
        List<Map<String, Object>> data = List.of(
                Map.of("label", "监测项目", "value", valueofjcxm, "unit", "项", "color", "#73C0DE"),
                Map.of("label", "监测安全天数", "value", valueofjcdays, "unit", "天", "color", "#FAC858")
        );
        return Result.success(data);
    }

    private int sumofyjcs;
    private int sumofxzyh;
    @GetMapping("/stats/warning")
    public Result<List<Map<String, Object>>> getWarningStats() {
        sumofyjcs = homePageService.getSumOfYjcs();
        sumofxzyh = homePageService.getSumOfXzyh();
        List<Map<String, Object>> data = List.of(
                Map.of("label", "总预警次数", "value", sumofyjcs, "unit", "次"),
                Map.of("label", "新增隐患点", "value", sumofxzyh, "unit", "处")
        );
        return Result.success(data);
    }

    private int redWarningCount;
    private int yellowWarningCount;
    private int blueWarningCount;
    private int orangeWarningCount;
    @GetMapping("/stats/warning-level")
    public Result<List<Map<String, Object>>> getWarningLevelStats() {
        int redWarningCount = homePageService.countRedWarning();
//        int redWarningCount = 50;
        int yellowWarningCount = homePageService.countYellowWarning();


//        System.out.println("-------------------------------------"+yellowWarningCount);

        int blueWarningCount = homePageService.countBlueWarning();

//        System.out.println("-------------------------------------"+blueWarningCount);

        int orangeWarningCount = homePageService.countOrangeWarning();

//        System.out.println("-------------------------------------"+orangeWarningCount);


//        int orangeWarningCount = 5;
        List<Map<String, Object>> data = new ArrayList<>();

        if (redWarningCount > 0) {
            System.out.println("-------------------------------------");
            data.add(Map.of("label", "红色双控预警", "value", redWarningCount, "color", "red"));
        }
        if (yellowWarningCount > 0) {
            data.add(Map.of("label", "黄色单控预警", "value", yellowWarningCount, "color", "yellow"));
        }
        if (orangeWarningCount > 0) {
            data.add(Map.of("label", "橙色单控预警", "value", orangeWarningCount, "color", "orange"));
        }
        if (blueWarningCount > 0) {
            data.add(Map.of("label", "蓝色预警", "value", blueWarningCount, "color", "blue"));
        }

        return Result.success(data);
    }


    @GetMapping("/stats/device-status")
    public Result<List<Map<String, Object>>> getDeviceStatusStats() {
//        int onlineDevices = slopeInfoService.countOnlineDevices();
//        int offlineDevices = slopeInfoService.countOfflineDevices();
        int total = slopeInfoService.getTotalCountDevice();
        int onlineDevices = (int)(total * 0.9); // 转换成整数

        int offlineDevices = (int)(total * 0.1);
        List<Map<String, Object>> data = List.of(
                Map.of("name", "在线", "value", onlineDevices, "color", "#91CC75"),
                Map.of("name", "离线", "value", offlineDevices, "color", "#EE6666", "offset", true)
        );
        return Result.success(data);
    }

    @GetMapping("/video/monitor")
    public Result<Map<String, String>> getVideoMonitor() {
        Map<String, String> data = Map.of("videoUrl", "https://yourcdn.com/path/to/video.mp4");
        return Result.success(data);
    }

    @GetMapping("/gaojing")
    public Result<List<gaojingtanchuang>> getGaojingTanchuang(HttpServletRequest request)
    {
//        List<gaojingtanchuang>
        System.out.println("当前登录用户：" + request.getHeader("X-Username"));
        String username = request.getHeader("X-Username");
        Long deptIds;
        deptIds = Long.parseLong(request.getHeader("X-DeptId"));
        System.out.println( "当前登录部门00000000000000000000000000000：" + deptIds);

        System.out.println( "当前登录部门         111111111111111111111           ：" + deptIds);
        return Result.success(slopeWarningInfoService.getGaojingTanchuang(username, deptIds));
    }


   @GetMapping("/map/point-info")
    public Result<clickWindow> getPointNumber(HttpServletRequest request) throws InvocationTargetException, IllegalAccessException {

        String username = request.getHeader("X-Username");
        Long deptIds = Long.parseLong(request.getHeader("X-DeptId"));
        String choice = request.getHeader("click");
        System.out.println("当前登录用户：" + username);
        return Result.success(slopeWarningInfoService.getTotalClinck(username,choice,deptIds));
    }

    // 获取报警信息列表
//    @GetMapping("/infoList")
//    public Result<List<DangerInfo>> getInfoList(@RequestHeader("X-Username") String username) {
//        List<DangerInfo> infoList = dangerService.getInfoListByUsername(username);
//        return ResponseEntity.ok(infoList);
//    }
//
//    // 获取报警总信息
//    @GetMapping("/totalInfo")
//    public Result<List<TotalInfo>> getTotalInfo(@RequestHeader("X-Username") String username) {
//        List<TotalInfo> totalInfo = dangerService.getTotalInfoByUsername(username);
//        return ResponseEntity.ok(totalInfo);
//    }


    @GetMapping("/environment")
    public Result<environment> getEnvironment()
    {
        environment environment = new environment();
        Instant now = Instant.now();
        environment.setUpdateTime(LocalDateTime.ofInstant(now, ZoneId.of("Asia/Shanghai")));
        environment.setTemperature(slopeInfoService.getTemperature());
        environment.setHumidity(slopeInfoService.getHumidity());
        environment.setDailyRainfall(slopeInfoService.getRainfall());
        return Result.success(environment);
    }

    @GetMapping("/realtime")
    public Result<ApiData> getData(HttpServletRequest request) {

//        String username = request.getHeader("X-Username");
        // 1. 构造数据项
        List<ApiData.Item> itemList = new ArrayList<>();
        //         模拟数据项
        ApiData.Item item = new ApiData.Item();
        String prov = slopeInfoService.getProvince();
        String[] parts = prov.split("国道");
        String result = parts[1].substring(0, 2); // 提取"绥满"
//            System.out.println("提取到的字符串: " + result);
        item.setXzqy(result);

        //  测点数量
        int cdsl =slopeInfoService.getCdsl();
        item.setCdsl(cdsl);
        //
//        int lxcd =slopeInfoService.getLxcd();
        item.setLxcd(5);
//        int yjcd =slopeInfoService.getYjcd();
        item.setYjcd(6);
        String slopeName = slopeInfoService.getSlopeNames();
        item.setSlopeName(slopeName);

        item.setStatus("base");
        itemList.add(item);

        // 2. 构造统计信息
        ApiData.Statistics statistics = new ApiData.Statistics();
        statistics.setNormal(1);    // 正常项目数量
        statistics.setAbnormal(0); // 异常项目数量

        // 3. 构造 ApiData
        ApiData apiData = new ApiData();
        apiData.setData(itemList);
        apiData.setTotal(itemList.size());
        apiData.setStatistics(statistics);

        // 4. 构造 Result 返回
        Result<ApiData> results = new Result<>(200, "成功", apiData);
        return results;
    }

    @GetMapping("/vedio")
    public Result<String> getVedio(HttpServletRequest request)
    {
        Long deptId = Long.valueOf(request.getHeader("X-DeptId"));
        String url = slopeInfoService.getVedio(deptId);
        if (url != null && !url.contains("错误代码"))
        {
            System.out.println("当前url==================："+  url);
            return Result.success(url);
        }else {
            System.out.println("当前url==================："+  url);
            return null;
        }
    }


    @GetMapping("/yjtongji")
    public Result<List<Map<String,Object>>> getYjtongji()
    {
        List<Map<String,Object>> list = new ArrayList<>();
//        Long deptId = Long.valueOf(request.getHeader("X-DeptId"));
        String yujingxiangmuzs = "预警项目总数"; // key_1
        String yujingxiangmuyh = "预警测点总数";  // key_2
        Map<String,Object> map1 = new HashMap<>();
        map1.put(yujingxiangmuzs,slopeInfoService.getYjxmzssss());

        Map<String,Object> map2 = new HashMap<>();
        map2.put(yujingxiangmuyh,slopeInfoService.getYjcdzssssssssss());

        list.add(map1);
        list.add(map2);

        return Result.success(list);
    }

    @GetMapping("/lixianshuju")
    public Result<List<lxshuju>> getLixianshuju()
    {
        List<lxshuju> list = new ArrayList<>();

        list = slopeInfoService.getLixianshuju();
        return Result.success(list);
    }

    @GetMapping("/sbtongji")
    public Result<List<sbtongji>> getSbtongji()
    {
        return Result.success(slopeInfoService.getSbtongji());
    }
//    @GetMapping("liefeng")
//    public Result<List<liefeng>> getLiefeng()
//    {
//    }

    @GetMapping("/pic")
    public Result<Map<String,List<String>>> getPic()
    {
        Map<String,List<String>> map = new HashMap<>();
//        map.put("博瓦",slopeInfoService.getPic());
//        map.put("三宝",slopeInfoService.getPic());

        /*
        左侧雷达监测： 最新的雷达抓拍：20张，带上日期标签
        中间背景：  雷达信息变形图
        右侧：{
        视频监测：1 定点摄像头 10个监控
                2 AI监测图像  博瓦最新的5，6张
        无人机图像
        }
        // 裂缝变化量 速率
         */

        return Result.success(map);

    }

    @GetMapping("/videosAll")
    public Result<List<vediosAlls>> getVideosAll()
    {
        return Result.success(slopeInfoService.getVideosAll());
    }

    // 无人机
    @GetMapping("/plane")
    public Result<List<wurenji>> getPlane()
    {
        return Result.success(slopeInfoService.getPlane());
    }


    @GetMapping("/AIjcshexiangtou")
    public Result<List<String>> getAIjcshexiangtou()
    {
        return Result.success(slopeInfoService.getAIjcshexiangtou());
    }
}
